import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
import { allConfig } from '@/config'
import Cookies from 'js-cookie'
import qs from 'qs'

/**
 * 消息提示
 */
export const messageBox = (msg: string, type?: any) => {
    ElMessage({
        message: msg,
        type: type || 'warning',
        duration: 2000,
    })
}

/**
 * @description 重定向到登录页面
 */

export function redirectLogin() {
    if (allConfig.isAllowRedirectLogin) {
        removeToken()
        let url = window.location.href.split('#')[0]
        if (url.includes('localhost')) {
            url = url.replace('http://', '').replace('/', '')
        }
        if (redirectLogin.redirect) {
            return
        }
        if (import.meta.env.DEV) {
            window.open(`${allConfig.loginUrl}`, '_blank')
        } else {
            window.location.href = `${allConfig.loginUrl}?redirectUrl=${encodeURIComponent(url)}`
        }
        redirectLogin.redirect = true
    }
}
redirectLogin.redirect = false

/**
 * 设置token到cookie中
 */
export const setToken = (token: string) => {
    Cookies.set(allConfig.tokenKey, token)
}

/**
 * 移除cookie的token
 */
export const removeToken = () => {
    Cookies.remove(allConfig.tokenKey)
}

/**
 * 读取缓存中的token
 */
export const getToken = () => {
    return Cookies.get(allConfig.tokenKey)
}

/**
 * 递归路由中的信息获取菜单
 */
export const getMenus = (routes: any[]) => {
    const results: any[] = []
    const worker = (arr: any[], menus: any[]) => {
        arr.forEach((item: any) => {
            if (item.meta && item.meta.isMenu) {
                const subs: any[] = []
                item.children && item.children.length ? worker(item.children, subs) : []
                menus.push({
                    label: item.meta.menuName,
                    code: item.name,
                    id: item.name,
                    subs,
                })
            }
        })
    }
    worker(routes, results)
    return results
}

/**
 * @param url 路径
 * @returns 参数
 */
export const parseUrlParams = (fullPath = '') => {
    const paramsUrl = fullPath.split('?')[1]
    const newObj: { [p in string]: any } = {}
    if (paramsUrl) {
        const obj = qs.parse(paramsUrl)
        Object.keys(obj).forEach((key: string) => {
            if (typeof obj[key] === 'string') {
                newObj[key] = decodeURIComponent(obj[key] as string)
            } else {
                newObj[key] = obj[key]
            }
        })
        return newObj
    }
    return newObj
}

/**
 * 添加url参数
 */
export const stringifyUrlParams = (params: { [p in string]: any } = {}) => {
    if (Object.keys.length) {
        const search = qs.stringify(encodeUrlParams(params))
        return `${search}`
    }
    return ''
}

/**
 * 格式化包装url参数
 */
export const encodeUrlParams = (params: { [p in string]: any } = {}) => {
    const newObj: { [p in string]: any } = {}
    if (Object.keys.length) {
        Object.keys(params).forEach((key: string) => {
            if (typeof params[key] === 'string') {
                newObj[key] = encodeURIComponent(params[key])
            } else {
                newObj[key] = params[key]
            }
        })
    }
    return newObj
}

/**
 * 输入表格数据和合并字段信息，返回合并信息
 */
export const mergeTableTool = (tableData: any[], mergeColumns: any[]) => {
    const tableMergeData: any = []
    const calculateRowIndex = (
        data: any,
        index: number,
        nextIndex: number,
        count: number,
        name: string,
    ): any => {
        // 比较当前单元格中的数据与同一列之后的单元格是否相同
        if (
            nextIndex < data.length &&
            data[index][name] &&
            data[nextIndex][name] &&
            data[index][name] === data[nextIndex][name]
        ) {
            return calculateRowIndex(data, index, ++nextIndex, ++count, name)
        }
        return count
    }
    const calculateColumnIndex = (
        data: any,
        index: number,
        nextIndex: number,
        count: number,
        maxLength: number,
    ): any => {
        // 比较当前单元格中的数据与同一行之后的单元格是否相同
        if (
            nextIndex < maxLength &&
            data[mergeColumns[index]['name']] &&
            data[mergeColumns[nextIndex]['name']] &&
            data[mergeColumns[index]['name']] === data[mergeColumns[nextIndex]['name']]
        ) {
            return calculateColumnIndex(data, index, ++nextIndex, ++count, maxLength)
        }
        return count
    }
    for (let i = 0; i < tableData.length; i++) {
        for (let j = 0; j < mergeColumns.length; j++) {
            let rowIndex = 1
            let columnIndex = 1
            if (
                j > 0 &&
                tableData[i][mergeColumns[j]['name']] &&
                tableData[i][mergeColumns[j - 1]['name']] &&
                tableData[i][mergeColumns[j]['name']] === tableData[i][mergeColumns[j - 1]['name']]
            ) {
                columnIndex = 0
            }
            if (
                i > 0 &&
                tableData[i][mergeColumns[j]['name']] &&
                tableData[i - 1][mergeColumns[j]['name']] &&
                tableData[i][mergeColumns[j]['name']] === tableData[i - 1][mergeColumns[j]['name']]
            ) {
                rowIndex = 0
            }
            // 比较横坐标右方元素
            if (columnIndex > 0) {
                columnIndex = calculateColumnIndex(tableData[i], j, j + 1, 1, mergeColumns.length)
            }
            // 比较纵坐标下方元素
            if (rowIndex > 0) {
                rowIndex = calculateRowIndex(tableData, i, i + 1, 1, mergeColumns[j]['name'])
            }
            const key = mergeColumns[j]['index'] + '_' + i
            tableMergeData[key] = [rowIndex, columnIndex]
        }
    }
    return tableMergeData
}

/**
 * 是否隐藏菜单
 */
export const isHideMenus = () => {
    // 设置菜单显示隐藏
    let bool = false
    if (window.location.href.includes('hideMenus=true') || window.top !== window) {
        bool = true
    } else {
        bool = false
    }
    return bool
}

/**
 * 将url上的token设置到本地
 */
export const setUrlTokenToCookie = () => {
    const urlParams = parseUrlParams(window.location.href)
    if (urlParams.token) {
        setToken(urlParams.token)
    }
}
